package controllers

import (
	"app/config"
	"app/daos"
	. "app/utils"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type Permission struct {
	Dashboard
}

// RoleList 4 permission/roleList 角色列表
func (permission *Permission) RoleList(c *gin.Context) gin.H {
	var roles []daos.Role
	if err := daos.GetConnection().Find(&roles); err.Error != nil {
		return permission.WarnResponse(1, err.Error.Error())
	}

	return permission.Response(gin.H{"role": roles})
}

// 5 permission/permission 权限策略列表

func (permission *Permission) Permission(c *gin.Context) gin.H {
	permissionMap := config.Cfg.Permission
	menuMap := config.Cfg.Menu
	return permission.Response(gin.H{"permission": permissionMap, "menu": menuMap})
}

// 6 permission/roleAdd 添加角色

func (permission *Permission) RoleAdd(c *gin.Context) gin.H {
	params, err := GetStructByParams[RoleAdd](c)
	if err != nil {
		return permission.WarnResponse(1, err.Error())
	}

	var roleModel daos.Role
	roleModel.Role = params.Role
	//开启事务
	transaction := daos.GetConnection().Begin()
	transaction.Create(&roleModel)
	//角色权限
	var rolePermissionS []daos.RolePermission
	if params.Permission != "" {
		permissionArr := Str2int32s(params.Permission)
		for _, v := range permissionArr {
			var rolePermission daos.RolePermission
			rolePermission.PermissionId = v
			rolePermission.RoleId = roleModel.ID
			rolePermissionS = append(rolePermissionS, rolePermission)
		}
	}

	//角色菜單
	if params.Menu != "" {
		menuArr := Str2int32s(params.Menu)
		for _, v := range menuArr {
			var rolePermission daos.RolePermission
			rolePermission.MenuId = v
			rolePermission.RoleId = roleModel.ID
			rolePermissionS = append(rolePermissionS, rolePermission)
		}
	}

	if len(rolePermissionS) != 0 {
		if err = transaction.Create(&rolePermissionS).Error; err != nil {
			transaction.Rollback()
			return permission.WarnResponse(2, err.Error())
		}
	}

	//提交事务
	transaction.Commit()
	return permission.Response(gin.H{})
}

// 7 permission/roleChange 修改角色

func (permission *Permission) RoleChange(c *gin.Context) gin.H {
	params, err := GetStructByParams[RoleChange](c)
	if err != nil {
		return permission.WarnResponse(1, err.Error())
	}

	var roleModel = new(daos.Role)
	//先查询是否存在该角色, 保存在模型变量roleModel中
	if err := daos.GetConnection().Where("id = ?", params.RoleId).Take(&roleModel).Error; gorm.ErrRecordNotFound == err {
		return permission.WarnResponse(2, "角色不存在")
	}

	roleModel.Role = params.Role
	//开启事务
	transaction := daos.GetConnection().Begin()
	//更新角色
	if err = transaction.Save(&roleModel).Error; err != nil {
		transaction.Rollback()
		return permission.WarnResponse(3, err.Error())
	}

	//删除旧数据
	transaction.Delete(&daos.RolePermission{}, "roleId = ?", params.RoleId)
	//更新角色权限表
	var rolePermissionS []daos.RolePermission
	if params.Permission != "" {
		permissionArr := Str2int32s(params.Permission)
		for _, v := range permissionArr {
			var rolePermission daos.RolePermission
			rolePermission.PermissionId = v
			rolePermission.RoleId = roleModel.ID
			rolePermissionS = append(rolePermissionS, rolePermission)
		}
	}

	//角色菜單
	if params.Menu != "" {
		menuArr := Str2int32s(params.Menu)
		for _, v := range menuArr {
			var rolePermission daos.RolePermission
			rolePermission.MenuId = v
			rolePermission.RoleId = roleModel.ID
			rolePermissionS = append(rolePermissionS, rolePermission)
		}
	}

	if len(rolePermissionS) != 0 {
		if err = transaction.Create(&rolePermissionS).Error; err != nil {
			transaction.Rollback()
			return permission.WarnResponse(4, err.Error())
		}
	}

	//提交事务
	transaction.Commit()
	return permission.Response(gin.H{})
}

// 8 permission/roleInfo 角色信息

func (permission *Permission) RoleInfo(c *gin.Context) gin.H {
	params, err := GetStructByParams[ID](c)
	if err != nil {
		return permission.WarnResponse(1, err.Error())
	}

	var roleModel = new(daos.Role)
	//先查询是否存在该角色, 保存在模型变量roleModel中
	if err = daos.GetConnection().Where("id = ?", params.Id).Take(&roleModel).Error; gorm.ErrRecordNotFound == err {
		return permission.WarnResponse(2, "角色不存在")
	}

	//查询角色权限
	var rolePermission []daos.RolePermission
	if err = daos.GetConnection().Where("roleId = ?", params.Id).Find(&rolePermission).Error; err != nil {
		return permission.WarnResponse(3, err.Error())
	}

	var permissionId []int32
	var menuId []int32
	for _, v := range rolePermission {
		if v.PermissionId != 0 {
			permissionId = append(permissionId, v.PermissionId)
		}

		if v.MenuId != 0 {
			menuId = append(menuId, v.MenuId)
		}
	}

	return permission.Response(gin.H{"role": roleModel.Role, "permission": Int32s2Str(permissionId), "menu": Int32s2Str(menuId)})
}

// 9 permission/roleDelete 删除角色

func (permission *Permission) RoleDelete(c *gin.Context) gin.H {
	params, err := GetStructByParams[ID](c)
	if err != nil {
		return permission.WarnResponse(1, err.Error())
	}

	var roleModel = new(daos.Role)
	//先查询是否存在该角色, 保存在模型变量roleModel中
	if err = daos.GetConnection().Where("id = ?", params.Id).Take(&roleModel).Error; gorm.ErrRecordNotFound == err {
		return permission.WarnResponse(2, "角色不存在")
	}

	//删除角色
	if err = daos.GetConnection().Delete(&roleModel).Error; err != nil {
		return permission.WarnResponse(3, err.Error())
	}

	return permission.Response(gin.H{})
}

// 10 permission/userList 用户列表

func (permission *Permission) UserList(c *gin.Context) gin.H {
	var users []daos.Admin
	if err := daos.GetConnection().Find(&users); err.Error != nil {
		return permission.WarnResponse(1, err.Error.Error())
	}

	return permission.Response(gin.H{"user": users})
}

// 11 permission/userAdd 添加用户

func (permission *Permission) UserAdd(c *gin.Context) gin.H {
	params, err := GetStructByParams[UserAdd](c)
	if err != nil {
		return permission.WarnResponse(1, err.Error())
	}

	//初始密码123456
	var userModel = new(daos.Admin)
	userModel.Username = params.Username
	userModel.Nickname = params.Nickname
	userModel.Password = HashPassword("123456")
	userModel.Enabled = 1
	userModel.IsAdmin = params.IsAdmin
	//开启事务
	transaction := daos.GetConnection().Begin()
	//插入用户
	if err = transaction.Create(&userModel).Error; err != nil {
		transaction.Rollback()
		return permission.WarnResponse(2, err.Error())
	}

	//插入用户角色表
	if params.Role != "" {
		var userRoles []daos.AdminRole
		roleArr := Str2intS(params.Role)
		for _, v := range roleArr {
			var userRole daos.AdminRole
			userRole.RoleId = v
			userRole.AdminId = userModel.ID
		}

		if err = transaction.Create(&userRoles).Error; err != nil {
			transaction.Rollback()
			return permission.WarnResponse(3, err.Error())
		}
	}

	//提交事务
	transaction.Commit()
	return permission.Response(gin.H{})
}

// 12 permission/userChange 修改用户

func (permission *Permission) UserChange(c *gin.Context) gin.H {
	params, err := GetStructByParams[UserChange](c)
	if err != nil {
		return permission.WarnResponse(1, err.Error())
	}

	var userModel = new(daos.Admin)
	if err = daos.GetConnection().Where("id = ? and deleted = 0", params.UserId).Take(&userModel).Error; gorm.ErrRecordNotFound == err {
		return permission.WarnResponse(2, "用户不存在")
	}

	userModel.Username = params.Username
	userModel.Nickname = params.Nickname
	userModel.IsAdmin = params.IsAdmin
	transaction := daos.GetConnection().Begin()
	if err = transaction.Save(&userModel).Error; err != nil {
		transaction.Rollback()
		return permission.WarnResponse(3, err.Error())
	}

	//删除旧数据
	transaction.Delete(&daos.AdminRole{}, "admin_id = ?", params.UserId)
	//插入用户角色表
	if params.Role != "" {
		var userRoles []daos.AdminRole
		roleArr := Str2intS(params.Role)
		for _, v := range roleArr {
			var userRole daos.AdminRole
			userRole.RoleId = v
			userRole.AdminId = userModel.ID
		}

		if err = transaction.Create(&userRoles).Error; err != nil {
			transaction.Rollback()
			return permission.WarnResponse(3, err.Error())
		}
	}

	//提交事务
	transaction.Commit()
	return permission.Response(gin.H{})
}

// 13 permission/userInfo 用户信息

func (permission *Permission) UserInfo(c *gin.Context) gin.H {
	params, err := GetStructByParams[ID](c)
	if err != nil {
		return permission.WarnResponse(1, err.Error())
	}
	//先查询是否存在该用户, 保存在模型变量userModel中
	var userModel = new(daos.Admin)
	if err = daos.GetConnection().Where("id = ?", params.Id).Take(&userModel).Error; gorm.ErrRecordNotFound == err {
		return permission.WarnResponse(2, "用户不存在")
	}

	//查询用户角色
	var userRole []daos.AdminRole
	if err = daos.GetConnection().Where("admin_id = ?", params.Id).Find(&userRole).Error; err != nil {
		return permission.WarnResponse(3, err.Error())
	}

	//获取角色ID数组，查询角色名称
	var roleId []int
	for _, v := range userRole {
		roleId = append(roleId, v.RoleId)
	}

	return permission.Response(gin.H{"username": userModel.Username, "nickname": userModel.Nickname, "role": IntS2Str(roleId), "enabled": userModel.Enabled})
}

// 14 permission/userDelete 删除用户

func (permission *Permission) UserDelete(c *gin.Context) gin.H {
	params, err := GetStructByParams[ID](c)
	if err != nil {
		return permission.WarnResponse(1, err.Error())
	}

	//先查询是否存在该用户, 保存在模型变量userModel中
	var userModel = new(daos.Admin)
	if err = daos.GetConnection().Where("id = ?", params.Id).Take(&userModel).Error; gorm.ErrRecordNotFound == err {
		return permission.WarnResponse(2, "用户不存在")
	}

	//开启事务
	transaction := daos.GetConnection().Begin()
	//删除用户
	if err = transaction.Delete(&userModel).Error; err != nil {
		transaction.Rollback()
		return permission.WarnResponse(3, err.Error())
	}

	//删除用户角色
	if err = transaction.Delete(&daos.AdminRole{}, "admin_id = ?", params.Id).Error; err != nil {
		transaction.Rollback()
		return permission.WarnResponse(4, err.Error())
	}

	//提交事务
	transaction.Commit()
	return permission.Response(gin.H{})
}

// 27 permission/userEnable 禁用启用

func (permission *Permission) UserEnable(c *gin.Context) gin.H {
	params, err := GetStructByParams[UserEnable](c)
	if err != nil {
		return permission.WarnResponse(1, err.Error())
	}

	var userModel = new(daos.Admin)
	userModel.ID = params.UserId
	userModel.Enabled = params.Enable
	if err = daos.GetConnection().Save(&userModel).Error; err != nil {
		return permission.WarnResponse(2, err.Error())
	}

	return permission.Response(gin.H{})
}

// 27 permission/userAdmin 是否为管理员

func (permission *Permission) UserAdmin(c *gin.Context) gin.H {
	sessionId := c.GetHeader("SESSION-ID")
	userId := SessionMagage.GetSessionVal(sessionId, "id")
	if SessionMagage.CheckSession(sessionId) == "" || userId == nil {
		return permission.Response(gin.H{"userId": "", "nickname": "", "isAdmin": 0, "menu": []map[string]interface{}{}, "permission": []map[string]interface{}{}, "sessionOut": 1})
	}

	//查询用户角色信息
	var userRole []daos.AdminRole
	if err := daos.GetConnection().Where("admin_id = ?", userId).Find(&userRole).Error; err != nil {
		return permission.WarnResponse(3, err.Error())
	}

	isAdmin := SessionMagage.GetSessionVal(sessionId, "isAdmin").(int8)
	var permissionList []float64
	var menuList []float64
	if isAdmin == 1 { //管理员所有权限菜单游戏
		for _, v := range config.Cfg.Permission {
			permissionList = append(permissionList, v["id"].(float64))
		}

		for _, v := range config.Cfg.Menu {
			menuList = append(menuList, v["id"].(float64))
		}
	} else if len(userRole) != 0 { //非管理员且有角色
		var roleId []int
		for _, v := range userRole {
			roleId = append(roleId, v.RoleId)
		}

		//查询角色权限
		var rolePermission []daos.RolePermission
		if err := daos.GetConnection().Where("role_id in ?", roleId).Find(&rolePermission).Error; err != nil {
			return permission.WarnResponse(3, err.Error())
		}

		for _, v := range rolePermission {
			if v.PermissionId != 0 {
				permissionList = append(permissionList, float64(v.PermissionId))
			}

			if v.MenuId != 0 {
				menuList = append(menuList, float64(v.MenuId))
			}
		}
	}

	return permission.Response(gin.H{"userId": SessionMagage.GetSessionVal(sessionId, "id"),
		"username":   SessionMagage.GetSessionVal(sessionId, "username"),
		"nickname":   SessionMagage.GetSessionVal(sessionId, "nickname"),
		"isAdmin":    SessionMagage.GetSessionVal(sessionId, "isAdmin"),
		"permission": Float64s2Str(permissionList), "menu": Float64s2Str(menuList), "sessionOut": 0})
}
